package com.cmwa.scbp.base.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.cmwa.scbp.base.constants.SysProp;
import com.cmwa.scbp.base.mvc.entity.Employee;
import com.cmwa.scbp.utils.SessionUtils;

public class GlobalFilter implements Filter {
	
	private SysProp sysProp;
	
	private String loginUrl;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		loginUrl = sysProp.getLoginUrl();
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		// 设置应用路径
		request.setAttribute("path", request.getContextPath());

		String requestURI = request.getRequestURI();
		
		List<String> excludeUrls = sysProp.getExcludeUrls();
		for (String excludeUrl : excludeUrls) {
			if(requestURI.indexOf(excludeUrl) != -1) {
				chain.doFilter(request, response);
				return;
			}
		}

		HttpSession session = request.getSession();
		Employee employee = (Employee) session.getAttribute(SessionUtils.SESSION_EMPLOYEE);
		if (employee == null || 
				StringUtils.isBlank(employee.getID()) || 
				!"STAR".equals(employee.getEmpStat()) ||
				employee.isDue()
			) {
			
			if ("XMLHttpRequest".equals(request.getHeader("x-requested-with"))) {
				responseAjaxFailedException(response, loginUrl);
			} else {
				response.sendRedirect(loginUrl);
			}
			return;
		} else {
			SessionUtils.setEmployee(employee);
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

	public void responseAjaxFailedException(HttpServletResponse response, String loginUrl) {
		try {
			PrintWriter out = response.getWriter();
			response.setStatus(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
			response.setContentType("application/json;charset=UTF-8");
			out.write(loginUrl);
			out.flush();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public SysProp getSysProp() {
		return sysProp;
	}

	public void setSysProp(SysProp sysProp) {
		this.sysProp = sysProp;
	}
	
}
